package com.jm.service;

import com.jm.model.Account;
import com.jm.model.Business;
import com.jm.model.Goods;
import com.jm.model.Order;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;

/**
 * @Author: lidong
 * @Description Dubbo业务发起方逻辑
 * @Date Created in 2019/9/5 18:36
 */
@Service
@Slf4j
public class BusinessServiceImpl implements BusinessService {

    @Reference(version = "1.0.0", timeout = 600000, check = false)
    private GoodsService goodsService;

    @Reference(version = "1.0.0", timeout = 600000, check = false)
    private OrderService orderService;

    @Reference(version = "1.0.0", timeout = 600000, check = false)
    private AccountService accountService;

    /**
     * 处理业务逻辑 正常的业务逻辑
     *
     * @param business
     */
    @GlobalTransactional(timeoutMills = 300000, name = "dubbo-gts-seata-example")
    @Override
    public void buy(Business business) {
        log.info("开始全局事务，XID = " + RootContext.getXID());
        Goods goods = new Goods();
        goods.setCommodityCode(business.getCommodityCode());
        goods.setCount(business.getCount());
        goodsService.decGoods(goods);
        Order order = new Order();
        order.setUserId(business.getUserId());
        order.setCommodityCode(business.getCommodityCode());
        order.setCount(business.getCount());
        order.setAmount(business.getAmount());
        orderService.createOrder(order);
        Account account = new Account();
        account.setUserId(business.getUserId());
        account.setAmount(business.getAmount());
        accountService.decAccount(account);
    }
}
